import numpy as np
import matplotlib.pyplot as plt
import qrcode
from pyzbar import pyzbar
from PIL import Image

jing_names = ["静止", "肝经", "肾经", "脾经", "肺经", "胃经", "胆经", "膀胱经", "大肠经", "三焦经", "小肠经", "心经", "心包经"]
class Jingluo:
    def __init__(self, name:str, data:np.ndarray):
        self.name = name
        self.data = data
        assert len(data) == 60

    def score(self):
        return int(self.data.mean())

    def plot(self, fig: plt.Figure = None):
        if fig is None:
            fig = plt.figure(figsize=(15, 10))
        ax = fig.subplots(1, 1)
        ax.plot(self.data)
        ax.set_ylim(40, 140)
        return fig
    
class WDWXReport:
    def __init__(self):
        self.contents = {}

    @classmethod
    def from_qrcode(self, qr_image:Image.Image|str):
        if isinstance(qr_image,str):
            qr_image = Image.open(qr_image)
        decoded_objects = pyzbar.decode(qr_image)
        if len(decoded_objects) > 0:
            report = WDWXReport()
            txt = decoded_objects[0].data.decode("utf-8")
            data = np.int32([int(elem) for elem in txt.split(' ')])
            for i, jing in enumerate(jing_names):
                report.contents[jing] = Jingluo(jing, data[i * 60: i * 60 + 60])

            return report

    @classmethod
    def from_file(self, filepath:str):
        with open(filepath, 'r', encoding="utf-8") as f:
            report = WDWXReport()
            for i in range(13):
                line = f.readline()
                num, name, score = line.split(' ')
                num = int(num)
                score = int(score)
                data = []
                for j in range(8):
                    data.extend([int(num) for num in f.readline().split(' ')])
                
                report.contents[name] = Jingluo(name, np.int32(data))
            return report
        
    @classmethod
    def from_string(cls, contents):
        data = np.int32([int(num) for num in contents.split(' ')])
        report = WDWXReport()
        for i, name in enumerate(jing_names):
            report.contents[name] = Jingluo(name, data[i * 60: i * 60 + 60])
        return report

    def make_qrcode(self):
        data = []
        for name in jing_names:
            data.extend(self.contents[name].data)

        qr_str = ' '.join([str(n) for n in data])
        return qrcode.make(qr_str)

if __name__ == '__main__':
    report = WDWXReport.from_file('./data.txt')
    qr_image = report.make_qrcode()
    qr_image.save("./qrcode.png")